<template>
  <div class="form-page">
    <Card :bordered="false" :dis-hover="true">
      <p slot="title" style="color: #666;">
        <span
          class="iconfont icon-changyongtubiao-xianxingdaochu-zhuanqu-"
          style="font-size: 20px;"
        ></span> 编辑优惠券
      </p>
      <p slot="extra" style="color: #999;font-size: 12px;">
        <label style="color: #FF3B30;">*</label> 为必填
      </p>

      <Form
        ref="formValidate2"
        :modelEdit="bloc.modelEdit"
        :rules="ruleValidate3"
        :label-width="111"
        style="padding:50px 100px 0 100px;width: 860px"
      >

        <FormItem label="品牌商:" prop="companyId" required v-if="tepee === '1'">
          <CompanySeletorSingle :companyId="bloc.modelEdit.companyId"
                                @on-change="value => companyChange(value)" v-if="tepee === '1'"></CompanySeletorSingle>
        </FormItem>
        <FormItem label="经销商:" prop="agentId" v-if="tepee === '1'">
          <i-select v-model="bloc.modelEdit.agentId" filterable @on-change="value => agentChange(value)" clearable>
            <i-option v-for="item in bloc.sortList" :value="item.id" :key="item.id">{{ item.agentName }}</i-option>
          </i-select>
        </FormItem>
        <FormItem label="优惠券名称:" prop="couponName" required>
          <Input v-model="bloc.modelEdit.couponName" placeholder="最多15个字" :maxlength="15"/>
        </FormItem>

        <FormItem class="timeLimit" label="优惠券使用期限:" required prop="TimeRadio">
          <div class="radio">
            <el-radio v-model="bloc.modelEdit.TimeRadio" :label="0">
              <FormItem style="display: inline-flex">
                <Input v-model="bloc.modelEdit.DayNum" type="number" style="width: 30%" class='daynum' :disabled="bloc.modelEdit.TimeRadio !== 0" @input="handleInput($event,1)"/> 天
              </FormItem>
            </el-radio>
          </div>
          <div class="radio" style="display: inline-flex;height: 40px">
            <el-radio v-model="bloc.modelEdit.TimeRadio" :label="1" class="TimeRadio2">
              <Row style="display: inline-flex;margin-top: 10px">
                <div style="margin:12px 5px 0 5px">
                  使用期限
                </div>
                <Col span="11">
                  <FormItem prop="startTime">
                    <DatePicker style="width: 100%;" type="datetime" format="yyyy-MM-dd" placeholder="开始时间" v-model="bloc.modelEdit.startTime" :disabled="bloc.modelEdit.TimeRadio !== 1"></DatePicker>
                  </FormItem>
                </Col>
                <Col span="2" style="text-align: center">-</Col>
                <Col span="11">
                  <FormItem prop="endTime">
                    <DatePicker style="width: 100%;" type="datetime" format="yyyy-MM-dd" placeholder="结束时间" v-model="bloc.modelEdit.endTime" :disabled="bloc.modelEdit.TimeRadio !== 1"></DatePicker>
                  </FormItem>
                </Col>
              </Row>
            </el-radio>
          </div>
          <div class="radio">
            <el-radio v-model="bloc.modelEdit.TimeRadio" :label="2">无限期使用</el-radio>
          </div>
        </FormItem>

        <FormItem label="会员:" prop="targetAccounts">
          <el-radio-group v-model="bloc.modelEdit.MemberRadio" @change="ChangeHandler">
            <el-radio :label="1">全部</el-radio>
            <el-radio :label="0">部分会员</el-radio>
            <el-radio :label="2">按生日月份分类</el-radio>
            <el-radio :label="3">按会员等级分类</el-radio>
          </el-radio-group>
<!--          <Transfer-->
<!--            v-if="bloc.modelEdit.MemberRadio===0"-->
<!--            :data="bloc.memberList"-->
<!--            :target-keys="bloc.modelEdit.targetAccounts"-->
<!--            filterable-->
<!--            :filter-method="filterMethod"-->
<!--            @on-change="handleChange2">-->
<!--          </Transfer>-->
          <Input v-if="bloc.modelEdit.MemberRadio===0" v-model="bloc.MemberString" @input="handlePhone($event)" placeholder="请输入,分隔的手机号"/>
          <MonthSelector v-if="bloc.modelEdit.MemberRadio===2" :targetAccounts="JSON.stringify(bloc.modelEdit.targetAccounts)" @change="Changed" style="width: 100%"></MonthSelector>
          <LvSelector v-if="bloc.modelEdit.MemberRadio===3" :targetAccounts="JSON.stringify(bloc.modelEdit.targetAccounts)" @change="Changed" style="width: 100%"></LvSelector>
        </FormItem>

        <FormItem label="可用商品:" prop="targetProducts">
          <el-radio v-model="bloc.modelEdit.ProductRadio" :label="1">全部</el-radio>
          <el-radio v-model="bloc.modelEdit.ProductRadio" :label="0">部分商品</el-radio>
          <el-radio v-model="bloc.modelEdit.ProductRadio" :label="2">按类别分类</el-radio>
          <ProductModelSelector v-if="bloc.modelEdit.ProductRadio===0" :targetProducts="JSON.stringify(bloc.modelEdit.targetProducts)" @change="Changed" style="width: 100%"></ProductModelSelector>
          <ProductCategorySelector v-if="bloc.modelEdit.ProductRadio===2" :targetProducts="JSON.stringify(bloc.modelEdit.targetProducts)" @change="Changed" style="width: 100%"></ProductCategorySelector>
        </FormItem>

        <label style="display:inline-flex;padding-left: 30px">
          <div style="color: #FF3B30;">*</div>
          <div style="padding-left: 3px;display: block"> 使用规则：</div>
        </label>

        <div style="display: inline-flex">
          <FormItem label="满" prop="condition" required>
            <Input v-model="bloc.modelEdit.condition" type="number" id="condition" @input="handleInput($event,2)"/>
          </FormItem>
          <FormItem label="减" prop="reduce" required>
            <Input v-model="bloc.modelEdit.reduce" type="number" id="reduce" @input="handleInput($event,3)"/>
          </FormItem>
        </div>

      </Form>
      <div style="margin: 20px 0px 35px 25px;">
        <Button style="width: 100px;height: 40px;" @click="handleCancel()">返回</Button>
        <AppButton
          ref="save"
          style="margin-left: 30px;width: 100px;height: 40px;"
          type="primary"
          :disabled="bloc.isDetail"
          @click="addModel('formValidate2')"
        >确认
        </AppButton>
      </div>
    </Card>
  </div>
</template>

<script lang="ts">
    import {Component, Vue} from 'vue-property-decorator';
    import {store} from '@/store/Store';
    import {baseUrl} from '@/base/Request';
    import {Route} from 'vue-router';
    import {FormBloc} from './FormBloc';
    import {isEmpty} from '@/base/util/Strings';
    import {AppButton} from '@/type/AppButton';
    import CompanySeletorSingle from '@/component/CompanySeletorSingle.vue';
    import ProductModelSelector from '@/component/ProductModelSelector.vue';
    import MonthSelector from '@/component/MonthSelector.vue'
    import LvSelector from '@/component/LvSelector.vue'
    import ProductCategorySelector from '@/component/ProductCategorySelector.vue'

    @Component({
        components: {CompanySeletorSingle, ProductModelSelector, ProductCategorySelector, MonthSelector, LvSelector}
    })

    export default class extends Vue {
        disabled: boolean = true;
        beforeRouteEnter(to: Route, from: Route, next: (vm: any) => void) {
            next(vm => {
                vm.bloc.type = vm.tepee;

                if (vm.tepee !== 1) {
                    // vm.bloc.getMemberData()
                }
                vm.bloc.load(vm.idx).then(res => {
                      vm.bloc.getProducts(vm.idx);
                      vm.bloc.getCompanyList(vm.bloc.company.pageIndex, vm.bloc.company.pageSize, 'ASC');
                      vm.bloc.getAllSort(vm.bloc.angent.pageIndex, 1000, 'DESC', vm.bloc.modelEdit.companyId);
                      vm.bloc.getMemberData();
                })
            });
        }
        bloc = new FormBloc();
        get idx() {
            return Number(this.$route.params.id);
        }
        get tepee() {
            return store.state.user.tepee
        }
        get uploadHeaders() {
            return {
                'Authorization': 'Bearer ' + store.state.auth.accessToken
            }
        };
        // get isHasMemberInfo() {
        //     const sessinStr = sessionStorage.getItem('MEMBER_INFO');
        //     const info = sessinStr ? JSON.parse(sessinStr) : undefined;
        //     if (info) {
        //         this.bloc.modelEdit.companyId = info[0].companyId;
        //         this.bloc.getAllSort(1, 1000, 'ASC', this.bloc.modelEdit.companyId);
        //         this.bloc.modelEdit.agentId = info[0].agentId;
        //         // this.bloc.modelEdit.targetAccounts = info.map((x) => x.id);
        //         // this.bloc.modelEdit.targetGroup = 'PART_MEMBER';
        //         this.bloc.isinfo = true;
        //     }
        //     return !isEmpty(info);
        // }

        validateId = (rule: any, value: string, callback: any) => {
            isEmpty(this.bloc.modelEdit.companyId) || this.bloc.modelEdit.companyId === 0
                ? callback(new Error('所属品牌商不能为空')) : callback();
        };
        validateAgentId = (rule: any, value: string, callback: any) => {
            isEmpty(this.bloc.modelEdit.agentId) || this.bloc.modelEdit.agentId === 0
                ? callback(new Error('所属经销商不能为空')) : callback();
        };
        // bloc.modelEdit.TimeRadio一一对应
        // 当daynum不为0时，开始和结束时间不能填写
        // 当daynum为0时，开始和结束时间必须都填写
        validateTime = (rule: any, value: string, callback: any) => {
            if (this.bloc.modelEdit.TimeRadio === 0 &&
                (this.bloc.modelEdit.DayNum <= 0 || isEmpty(this.bloc.modelEdit.DayNum))) {
                this.bloc.modelEdit.startTime = '';
                this.bloc.modelEdit.endTime = '';
                callback(new Error('请输入有效天数'));
            } else if (this.bloc.modelEdit.TimeRadio === 1 &&
                (this.bloc.modelEdit.startTime === '' || this.bloc.modelEdit.endTime === '')) {
                this.bloc.modelEdit.DayNum = 0;
                callback(new Error('请输入使用期限'));
            } else if (this.bloc.modelEdit.TimeRadio === 1 &&
                (this.bloc.modelEdit.startTime >= this.bloc.modelEdit.endTime)) {
                this.bloc.modelEdit.DayNum = 0;
                callback(new Error('开始时间不能大于等于结束时间'));
            } else {
                callback();
            }
        };
        validateMember = (rule: any, value: string, callback: any) => {
            if (this.bloc.modelEdit.MemberRadio !== 1 && this.bloc.modelEdit.targetAccounts.filter(Boolean).length === 0) {
                callback(new Error('请选择发放的会员范围'));
            } else {
                callback();
            }
        };
        validateProduct = (rule: any, value: string, callback: any) => {
            if (this.bloc.modelEdit.ProductRadio !== 1 && this.bloc.modelEdit.targetProducts.filter(Boolean).length === 0) {
                callback(new Error('请选择将发放优惠券的商品范围'));
            } else {
                callback();
            }
        };
        validateCondition = (rule: any, value: string, callback: any) => {
            if (this.bloc.modelEdit.condition <= 0) {
                callback(new Error('优惠条件不能为0'));
            } else {
                callback();
            }
        };
        validateReduce = (rule: any, value: string, callback: any) => {
            if (this.bloc.modelEdit.reduce <= 0) {
                callback(new Error('优惠金额不能小于等于0'));
            } else if (this.bloc.modelEdit.reduce >= this.bloc.modelEdit.condition) {
                callback(new Error('优惠金额不能大于等于优惠条件'));
            } else {
                callback();
            }
        };
        validateName = (rule: any, value: string, callback: any) => {
            if (this.bloc.modelEdit.CouponName === 0) {
                callback(new Error('优惠券名称不能为空'));
            } else {
                callback();
            }
        };
        ruleValidate3: any = {
            companyId: [{validator: this.validateId, trigger: 'blur'}],
            couponName: [{validator: this.validateName, trigger: 'blur'}],
            condition: [{validator: this.validateCondition, trigger: 'blur'}],
            reduce: [{validator: this.validateReduce, trigger: 'blur'}],
            TimeRadio: [{validator: this.validateTime, trigger: 'blur'}],
            targetAccounts: [{validator: this.validateMember, trigger: 'blur'}],
            targetProducts: [{validator: this.validateProduct, trigger: 'blur'}]
        };
        $refs!: {
            save: AppButton
            formValidate2: HTMLFormElement
        };
        enable = false;
        handleChange2 (targetKeys:[], direction:String, moveKeys:[]) {
            this.bloc.modelEdit.targetAccounts = targetKeys;
        }
        filterMethod (data, query) {
            return data.label.indexOf(query) > -1;
        }

        companyChange(companyId: number) {
            this.bloc.modelEdit.companyId = companyId;
            this.bloc
                .getAllSort(this.bloc.angent.pageIndex, 1000, 'DESC', companyId)
                .finally(() => {});
        }
        agentChange(agentId: Number) {
            // this.bloc.getMemberByAgentId(agentId);
        }
        // 添加
        addModel(name) {
            this.$refs[name].validate(valid => {
                if (valid) {
                    this.$refs.save.bloc.loading = true;
                    if (this.bloc.modelEdit.TimeRadio === 1 && !isEmpty(this.bloc.modelEdit.startTime) && !isEmpty(this.bloc.modelEdit.endTime)) {
                        this.bloc.getDaynum2(this.bloc.modelEdit.startTime, this.bloc.modelEdit.endTime)
                    }
                    if (this.bloc.modelEdit.TimeRadio === 2) {
                        this.bloc.modelEdit.DayNum = 0;
                        this.bloc.modelEdit.startTime = '';
                    }
                    if (!this.bloc.modelEdit.agentId) {
                        this.bloc.modelEdit.agentId = 1;
                    }
                    this.bloc.modelEdit.targetAccountsIn = [];
                    this.bloc.modelEdit.targetAccountsOut = [];
                    if (this.bloc.modelEdit.MemberRadio === 0 && this.bloc.modelEdit.targetAccounts.length !== 0) {
                        this.bloc.modelEdit.targetAccounts.map(item => {
                            if (this.bloc.memberSet.has(item)) {
                                this.bloc.modelEdit.targetAccountsIn.push(item);
                            } else {
                                this.bloc.modelEdit.targetAccountsOut.push(item);
                            }
                        })
                    }
                    console.log(this.bloc.memberSet);
                    console.log(this.bloc.modelEdit);
                    this.bloc.editModel(this.bloc.modelEdit).then(res => {
                        this.$Message.success('修改成功');
                        this.$refs.save.bloc.loading = false;
                        this.handleCancel();
                    }).catch(err => {
                        // this.$Message.error('保存失败');
                        this.$Message.error(err.message || 'error');
                        this.$refs.save.bloc.loading = false;
                    });
                }
            });
        }

        Changed(val, sym) {
            if (!sym) {
                this.bloc.modelEdit.targetAccounts = [];
                val.forEach((item) => {
                    this.bloc.modelEdit.targetAccounts.push(item[0])
                });
            } else if (sym === 1) { // 设备型号
                this.bloc.modelEdit.targetProducts = [];
                val.forEach((item) => {
                    this.bloc.modelEdit.targetProducts.push(item[1])
                });
            } else { // 设备类别
                this.bloc.modelEdit.targetProducts = [];
                val.forEach((item) => {
                    this.bloc.modelEdit.targetProducts.push(item[0])
                });
            }
        }
        ChangeHandler(val) {
            this.bloc.modelEdit.targetAccounts = [];
            this.bloc.modelEdit.MemberRadio = val;
            if (val === this.bloc.CurrentMemberRadio) {
                this.bloc.modelEdit.MemberRadio = this.bloc.CurrentMemberRadio;
                this.bloc.modelEdit.targetAccounts = this.bloc.CurrentMemberGroup;
            }
        }
        handleCancel() {
            this.$router.push({path: `/coupons`});
        }
        handleInput(v, e) {
            const cleanedValue = v.replace(/[^0-9]/g, '');
            const positiveInteger = cleanedValue.startsWith('-') ? parseInt(cleanedValue.substring(1), 10) || 0 : parseInt(cleanedValue, 10)
            this.$nextTick(() => {
                switch (e) {
                    case 1: this.bloc.modelEdit.DayNum = positiveInteger; break;
                    case 2: this.bloc.modelEdit.condition = positiveInteger; break;
                    case 3: this.bloc.modelEdit.reduce = positiveInteger; break;
                }
            });
        }
        handlePhone(v) { // 获取输入框中的值
            this.bloc.modelEdit.targetAccounts = [];
            let contain = this.bloc.MemberString.includes('，');
            const phoneReg = /^(?:(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8})(?:,(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8})*$/;
            // if (!phoneReg.test(this.bloc.MemberString)) { this.bloc.MemberString = ''; }
            if (contain) {
                this.$Message.error('不能含有中文逗号');
            }
            const rawNumbers = this.bloc.MemberString.split(',');
            this.bloc.modelEdit.targetAccounts = rawNumbers.filter(number => phoneReg.test(number));
            if (this.bloc.modelEdit.targetAccounts.length === 1000) {
                this.$Message.error('一次性只能录入1000个手机号');
            }
        }
    }
</script>

<style lang="less" scoped>
  /deep/ .ivu-form-item-content {
    justify-content: start !important;
    align-items: center !important;
  }
  /deep/ .ivu-form-item-label {
    padding-top: 0;
  }
  .video {
    display: flex;
  }
  /deep/ .ivu-transfer-list{
    width: 235px;
    height: 300px;
  }
  /deep/ .el-radio__inner {
    margin: 12px 0;
  }
  .TimeRadio2 /deep/ .el-radio__inner {
    margin-top: 0;
    margin-bottom: 30px;
  }
  .timeLimit /deep/ .ivu-form-item-label {
    display: contents;
  }
  /deep/ .ivu-transfer-list-body {
    padding-top: 50px;
  }
</style>
